#include "Bus.h"

bool Bus::isFull() {
    if(isRunning()){
        return true;
    }
    TimeTableItem& r = getCurrentRunningTableItem();
    if(r.getActualCarring() >= carrying)
    {
        return true;
    }
    return false;
}

void Bus::startADay() {
    runningTableNow = new RunningTable;
    //clone
    *runningTableNow = protoRunningTable;
    //runningTableNow->setDate(today);
}
void Bus::endADay() {
    numberOfItem = 0;
    state = waiting;
    RunningTable *a = getRunningTable();
    double timeRate = a->getTimeRate();
    double carryRate = a->getCarryRate(carrying);
    std::cout<<"载客率："<<carryRate<<endl;
    std::cout<<"发车准时率："<<timeRate<<endl;
    delete runningTableNow;
}
void Bus::addPerson() {
    if(isFull()){
        return;
    }
    TimeTableItem& r = getCurrentRunningTableItem();
    r.addCarring();
}

bool Bus::ifRun(const Time &now)
{
//    if(state == waiting){
//        TimeTableItem& r = getCurrentRunningTableItem();
//        int delta = rand() % 7 - 3;
//        const Time& dueToStart = r.getStartTime();
//        if((dueToStart - now) >= delta){
//            return true;
//        }else if((dueToStart - now) >= 5){
//            return true;
//        }else{
//            return false;
//        }
//    }else{
//        return false;
//    }
    TimeTableItem& r = getCurrentRunningTableItem();
    if((now - r.getStartTime()) == 0)
    {
        return true;
    }
    return false;
}
//试图发车
bool Bus::tryRun(const Time &now) {
    //生成随机数，生成随机数5分钟左右可发车
    TimeTableItem& r = getCurrentRunningTableItem();
    int randNum = rand()%11 - 5;
    int deltaMinute = (now - r.getStartTime());
    if(state != waiting) {
        return false;
    }else if(deltaMinute*deltaMinute <= randNum*randNum || deltaMinute >= 5){
        state = run;
        r.setStartTime(now);
        r.setEndTime(now + running);
        return true;
    }
    return false;
}
//试图提前停车
bool Bus::tryStop(const Time &now) {
    TimeTableItem& r = getCurrentRunningTableItem();
    if(state == waiting){
        return false;
    }else if((now - r.getEndTime()) == 0){
        state = waiting;
        numberOfItem++;
        return true;
    }
    return false;
}

//试图下班
bool Bus::tryEnd(const Time &now) {
    TimeTableItem& r = getCurrentRunningTableItem();
    if((now - r.getEndTime()) <= 0 && times == (numberOfItem+2)){
        endADay();
        return true;
    }
    return false;
}
